package service

import (
	"context"
	"errors"
	"sort"

	commonTools "algo-sdk-go/common/tools"
	"algo-sdk-go/project/matchmaking/application/dto"
	"algo-sdk-go/project/matchmaking/domain/models/entity"
)

// match
func (m *MatchMakingDomain) UserMapping(ctx context.Context, userNum int) ([]dto.UserAllInfo, error) {
	var (
		curUser             dto.UserAllInfo
		matchedUserList     []dto.UserAllInfo
		resultUserList      []dto.UserAllInfo
		matchedUserInfoList []entity.UserProfile
	)

	// 用户信息
	userInfoList, err := m.LoadUserAllInfo(ctx, []int{userNum})
	if err != nil {
		return nil, err
	}
	if len(userInfoList) == 0 {
		return nil, errors.New("未查询到用户信息")
	}
	curUser = userInfoList[0]

	// 匹配的用户信息
	matchedUserInfoList, err = m.userProfileRepo.LoadUserProfileByCondition(ctx, curUser.GetUserProfileCommand())
	if err != nil {
		return nil, err
	}
	matchedUserList, err = m.LoadUserAllInfo(ctx, commonTools.Cast(matchedUserInfoList, entity.LoadUserProfileUserNum))
	if err != nil {
		return nil, err
	}
	if len(matchedUserList) == 0 {
		return nil, errors.New("未查询到匹配的用户信息")
	}

	// 匹配
	for _, matchedUser := range matchedUserList {
		if curUser.Match(matchedUser) {
			resultUserList = append(resultUserList, matchedUser)
		}
	}

	// 排序
	sort.Sort(dto.UserAllInfoList(resultUserList))
	if len(resultUserList) > 10 {
		resultUserList = resultUserList[:10]
	}
	return resultUserList, nil
}
